# !/usr/bin/env python
# -*- coding:utf-8 -*-
'''
目标:
    读取163网站上主要财务指标数据

读取的数据类型:
    lrb - 利润表
    zcfzb - 资产负债表
    xjllb - 现金流量表
    cwbbzy - 财务报表摘要
    zycwzb - 主要财务指标

历史:
    2019-05-18 姚彧 创建
'''
__all__ = ['CN163Tool']

import numpy as np
import pandas as pd
from pandas.compat import StringIO
import requests


def _day2quater(day):
    day = day.split('-')
    year, month = day[:2]
    month = (int(month) + 2) // 3
    assert 0 < month < 5
    return '%s%02d' % (year, month)


class CN163Tool(object):
    def __init__(self, transpose=True):
        self.transpose = transpose


    def read_stock(self, stock_code, name='zycwzb'):
        r = requests.get('http://quotes.money.163.com/service/%s_%s.html?type=report' % (name, stock_code))
        if r.status_code == 200:
            return self.read_csv(StringIO(r.text.strip()))
        else:
            r.raise_for_status()

    def read_csv(self, filepath_or_buffer, *args, **kwargs):
        df = pd.read_csv(filepath_or_buffer, *args, **kwargs).replace('--', np.nan)
        if self.transpose:
            df = df.set_index(df.columns[0]).stack().unstack(0)
            df.index = [_day2quater(i) for i in df.index]
        df = df.apply(pd.to_numeric, errors='ignore')
        return df
